package j_applicationEvent;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 定义StudentAddBean触发StudentAddEvent事件
 * 新建StudentAddBean类，实现接口ApplicationContextAware中的setApplicationContext方法
 * 在构造bean的时候注入Spring的上下文对象，以便通过Spring上下文对象的publishEvent方法来触发StudentAddEvent事件，具体代码如下：
 * @author Y
 *
 */
public class StudentAddBean implements ApplicationContextAware{
	
	/* 定义Spring上下文对象 */
	private ApplicationContext m_applicationContext = null;
	
	/**
	 * 实现setApplicationContext(),注入ApplicationContext
	 */
	@Override
	public void setApplicationContext(ApplicationContext _applicationContext)
			throws BeansException {
		this.m_applicationContext = _applicationContext;
	}
	
	public void addStudent(String sStudentName){
		//1.构造一个增加学生的事件
		StudentAddEvent studentAddEvent = new StudentAddEvent(m_applicationContext, sStudentName);
		//2.触发增加学生事件
		m_applicationContext.publishEvent(studentAddEvent);
		
	}
	
	
	public static void main(String[] args) {
		String[] xmlConfig = new String[]{"applicationContext.xml"};
		//使用applicationContext 初始化系统
		ApplicationContext context = new ClassPathXmlApplicationContext(xmlConfig);
		StudentAddBean studentBean = (StudentAddBean) context.getBean("StudentAddBean");
		studentBean.addStudent("我是添加的第一个学生");
		studentBean.addStudent("我是添加的第二个学生");
		
		
		
	}
	
	

}
